package com.example.weather.activity;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.TextView;

import com.example.weather.Adapter.GridViewAdapter;
import com.example.weather.R;
import com.example.weather.interfaceimpl.CalendarOperator;
import com.example.weather.utils.ConstantsUtil;
import com.example.weather.utils.DataHelper;
import com.example.weather.utils.LunarCalendar;
import com.example.weather.utils.SpecialCalendar;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class CalendarActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
    private GestureDetector gestureDetector;
    private GridView gridView = null;
    private TextView topText = null;
    private int mCurrentYear = 0;
    private int mCurrentMonth = 0;
    private int mCurrentDay = 0;
    private String currentDate = "";
    private LunarCalendar mLunarCalendar;
    private TextView mLeftTextView;
    private TextView mRightTextView;

    private ArrayList<Map<String,Object>> arrayList;
    private Set<Integer> set;
    private boolean isLeapyear = false;  //是否为闰年
    private int daysOfMonth = 0;      //某月的天数
    private int dayOfWeek = 0;
    private GridViewAdapter mGridViewAdapter;
    private DataHelper mDataHelper;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.calendar);

        mDataHelper = DataHelper.getInstance(getApplicationContext());
        Calendar c = Calendar.getInstance();
        set = new HashSet<>();
        ClickListener clickListener = new ClickListener();
        mCurrentYear = c.get(Calendar.YEAR);
        mCurrentMonth = c.get(Calendar.MONTH);
        mCurrentDay = c.get(Calendar.DAY_OF_MONTH);
        arrayList = new ArrayList<>();

        gestureDetector = new GestureDetector(this);
        mLunarCalendar = new LunarCalendar();
        gridView = (GridView)findViewById(R.id.gridview);
        topText = (TextView) findViewById(R.id.tv_month);
        mLeftTextView = (TextView) findViewById(R.id.tv_left);
        mRightTextView = (TextView) findViewById(R.id.tv_right);

        mLeftTextView.setOnClickListener(clickListener);
        mRightTextView.setOnClickListener(clickListener);
        mGridViewAdapter = new GridViewAdapter(this, arrayList,new CalendarOperator(),new Handler());
        changeTitleTextView();
        addGridView();
        getAdapterData();
        gridView.setAdapter(mGridViewAdapter);
    }

    private class ClickListener implements View.OnClickListener {
        public void onClick(View v) {
            if (v.getId() == R.id.tv_left) {
                toOldMonth();
                changeTitleTextView();
                getAdapterData();
            }else if (v.getId() == R.id.tv_right) {
                toNewMonth();
                changeTitleTextView();
                getAdapterData();
            }
        }
    }

    //添加gridview
    private void addGridView() {
        gridView.setOnTouchListener(new View.OnTouchListener() {
            //将gridview中的触摸事件回传给gestureDetector
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // TODO Auto-generated method stub
                return CalendarActivity.this.gestureDetector.onTouchEvent(event);
            }
        });
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            //gridView中的每一个item的点击事件
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
                if (position >= dayOfWeek && position < daysOfMonth + dayOfWeek) {
                    boolean isExistPlan = set.contains(Integer.parseInt((String) arrayList.get(position).get("Date")));
                    Intent intent = new Intent(CalendarActivity.this, AddpPlanActivity.class)
                            .putExtra("isExist", isExistPlan)
                            .putExtra("year", mCurrentYear)
                            .putExtra("month", mCurrentMonth)
                            .putExtra("date", position - dayOfWeek + 1);
                    startActivityForResult(intent, ConstantsUtil.REQUEST_DATA);
                }
            }
        });
    }

    // 回调方法，从第二个页面回来的时候会执行这个方法
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // 根据上面发送过去的请求码来区别
        switch (requestCode) {
            case ConstantsUtil.REQUEST_DATA:
                getAdapterData();
                break;
            default:
                break;
        }
    }

    //添加头部的年份 闰哪月等信息
    public void changeTitleTextView(){
        String dateString = mCurrentYear + "年" + mCurrentMonth + "月";
        topText.setText(dateString);
        topText.setTextColor(Color.WHITE);
        topText.setTypeface(Typeface.DEFAULT_BOLD);
    }


    private void getAdapterData(){
        arrayList.clear();
        set = mDataHelper.getHavePlanDate(mCurrentYear,mCurrentMonth);
        isLeapyear = SpecialCalendar.isLeapYear(mCurrentYear);              //是否为闰年
        daysOfMonth = SpecialCalendar.getDaysOfMonth(isLeapyear, mCurrentMonth);  //某月的总天数
        dayOfWeek = SpecialCalendar.getWeekdayOfMonth(mCurrentYear, mCurrentMonth);      //某月第一天为星期几
        Map<String,Object> map = new HashMap<>();
        for(int i = 0 ; i< 42; i ++ ){
            if(i < dayOfWeek||i>=daysOfMonth+dayOfWeek){
                map.put("isExist",false);
            }else{
                if(set.size() != 0 && set.contains(i - dayOfWeek + 1)){
                    map.put("isHavePlan",true);
                }else{
                    map.put("isHavePlan",false);
                }
                map.put("isExist",true);
                String day = String.valueOf(i-dayOfWeek+1);   //得到的日期
                String lunarDay = mLunarCalendar.getLunarDate(mCurrentYear, mCurrentMonth, i-dayOfWeek+1,false);
                map.put("Date",day);
                map.put("LunarDate",lunarDay);
                if(i%7 == 0 || i%7 == 6){
                    map.put("isWeekend",true);
                }else{
                    map.put("isWeekend",false);
                }
            }
            arrayList.add(map);
            map = new HashMap<>();
        }
        mGridViewAdapter.notifyDataSetChanged();
    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        if (e1.getX() - e2.getX() > 120) {
            toNewMonth();
            changeTitleTextView();
            getAdapterData();
            return true;
        } else if (e1.getX() - e2.getX() < -120) {
            toOldMonth();
            changeTitleTextView();
            getAdapterData();
            return true;
        }
        return false;
    }

    private void toOldMonth(){
        if(mCurrentMonth >= 2 ){
            mCurrentMonth -- ;
        }else{
            mCurrentMonth = 12;
            mCurrentYear--;
        }
    }

    private void toNewMonth(){
        if(mCurrentMonth <= 11 ){
            mCurrentMonth ++ ;
        }else{
            mCurrentMonth = 1;
            mCurrentYear ++;
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {

        return this.gestureDetector.onTouchEvent(event);
    }

    @Override
    public boolean onDown(MotionEvent e) {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public void onLongPress(MotionEvent e) {
        // TODO Auto-generated method stub

    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
                            float distanceY) {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public void onShowPress(MotionEvent e) {
        // TODO Auto-generated method stub
    }

    @Override
    public boolean onSingleTapUp(MotionEvent e) {
        // TODO Auto-generated method stub
        return false;
    }

}
